/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-09-16
 * Time: 12:48
 */

// 两个线程交替打印
public class test2 {
    private static final int FINAL_NUMBER = 100;

    // 锁
    private static Object lock = new Object();

    private static int currentNum = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            while (currentNum<FINAL_NUMBER){
                synchronized (lock){
                    while (currentNum%2==0){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("t1:"+currentNum);
                    currentNum++;
                    lock.notify();
                }
            }
        });

        Thread t2 = new Thread(()->{
            while (currentNum<FINAL_NUMBER){
                synchronized (lock){
                    while (currentNum%2!=0){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("t2:"+currentNum);
                    currentNum++;
                    lock.notify();
                }
            }
        });

        t1.start();
        t2.start();
    }


}
